import {httpInstance} from "@/api/index";
import {getRefreshToken,setToken} from "@/lib/tokenUtil";
import { Message } from 'element-ui';
import router from '@/router/index'
import {invalidToken} from "@/lib/tokenUtil";

//登录
export const login = (username,password) =>{
   return httpInstance.request({
        url:"/authentication",
        method:"post",
        data:{
            username:username,
            password:password
        }
    })
}

/* token刷新请求 */
export const doRefreshToken = (refresh_token) =>{
    return httpInstance.request({
        url:"/refreshToken",
        method:"post",
        data:{
            refreshToken:refresh_token
        }
    })
}


export  const refreshToken = () =>{
    return new Promise(resolve =>{
        doRefreshToken(getRefreshToken()).then(res =>{
            setToken(res.data)
            resolve();
        }).catch(error =>{
            // 出现错误，说明refresh_token已经过期了，清空token，然后重定向到登录页面
            if(router.history.current.path !== "/login"){
                /* 当token过期时，打开新的页面可能会触发多个refresh_token刷新
                此时会多次调用导致多次重定向到index，因此判断当前路径不是login时才跳转 */
                Message.warning({
                    message:"登录超时，请重新登录"
                })
                invalidToken("")
                router.push("/login")
            }

        });
    })
}

//获取系统的菜单信息
export const getAdminMenu= () =>{
    return httpInstance.request({
        url:"/sys_admin_menu/getMenuTree",
        method:"get"
    })
}